import { inject, ref, watch } from 'vue'
import Configuration from '@/api/client/configuration.js'
import { SURE_TO_DELETE } from '@/constants/message.js'
export function useAccountManager(id) {
  const { Modal } = inject('Feedback')
  // AM 候选人
  const accountManagerLoading = ref(true)
  const accountManagerCandidates = ref([])
  Configuration.getAccountManagerCandidates(id).then(({ data }) => {
    accountManagerCandidates.value = data
  })
  const accountManagers = ref([])
  const getGetAccountManagers = () => {
    Configuration.getAccountManagers(id)
      .then(({ data }) => {
        accountManagers.value = data
      })
      .finally(() => {
        accountManagerLoading.value = false
      })
  }
  const handleDeleteAccountManager = userId => {
    Modal.confirm({
      content: SURE_TO_DELETE,
      okButtonProps: { danger: true },
      onOk: () => {
        Configuration.deleteAccountManager(id, userId).then(() => {
          getGetAccountManagers()
        })
      }
    })
  }
  getGetAccountManagers()
  const accountManagerCandidatesChoose = ref(null)
  watch(
    () => accountManagerCandidatesChoose.value,
    () => {
      if (accountManagerCandidatesChoose.value) {
        Configuration.addAccountManager(id, accountManagerCandidatesChoose.value).then(() => {
          getGetAccountManagers()
        })
        accountManagerCandidatesChoose.value = null
      }
    }
  )
  return {
    accountManagerCandidates,
    accountManagerCandidatesChoose,
    accountManagers,
    accountManagerLoading,
    handleDeleteAccountManager
  }
}
